package com.ny.controller;

import com.ny.entity.Classrooms;
import com.ny.entity.Reservations;
import com.ny.entity.Users;
import com.ny.service.ClassroomService;
import com.ny.service.ReservationService;
import com.ny.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private ReservationService reservationService;
    @Autowired
    private ClassroomService classroomService;
    @Autowired
    private UserService userService;
    // 管理员登录
    @RequestMapping("adminLogin")
    public String adminLogin(@RequestParam String username, @RequestParam String password, Model model, HttpSession session){
        System.out.println(username);
        System.out.println(password);
        Users user =  userService.login(username,password);
        session.setAttribute("user", user);
        System.out.println(user);
        System.out.println(user.getRole());
        if (user!= null && user.getRole().equals("管理员") ){
            List<Reservations> reservationList = reservationService.findAllReservations();
            model.addAttribute("reservationList", reservationList);
            return "reservations";
        }
        else {
            model.addAttribute("error", "请重新输入用户名和密码");
            return "login";
        }
    }
    @GetMapping("/approveReservation")
    public String approveReservation(@RequestParam("reservationId") int reservationId,@RequestParam int classroomId) {
        reservationService.updateReservationStatus(reservationId, "已通过", null);
        classroomService.updateClassroomStatusById(classroomId, "已预约");
        return "redirect:/reservations";
    }
    @PostMapping("/rejectReservation")
    public String rejectReservation(@RequestParam("reservationId") int reservationId, @RequestParam("rejectReason") String rejectReason,@RequestParam int classroomId) {
        reservationService.updateReservationStatus(reservationId, "不通过", rejectReason);
//        int classroomId = reservationService.getReservationById(reservationId);
        classroomService.updateClassroomStatusById(classroomId, "不通过");
        return "redirect:/reservations";
    }
}

